<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('商品库')" />
	<th:block th:include="include :: businessCSS" />
	<style>

		.preservationBtn{padding: 10px;text-align: center;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 10px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;}
		.layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .importTable{empty-cells:show;border-collapse:collapse;border-spacing:0;}
		.listext th{background:#eee;color:#3366cc;}
		.listext th,.listext td{border:solid 1px #ddd;text-align:left;padding:10px;font-size:14px;}

	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
	    <div class="north" style="background-color: #fff;">
			<div class="forminput"></div>
			<div class="layui-form-item preservationBtn" th:if="${enableEdit} == 1">
				<input type="button" lay-submit lay-filter="btn-edit" id="btn-edit" value="修改">
			</div>

    	</div>
		
    </form>
	</div>
</div>

<div>
    <table class="layui-hide" id="zjdhtable" lay-filter="zjtable"></table>
    <script type="text/html" id="barDh">
        <button class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除</button>
    </script>
    <script type="text/html" id="zjtoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">子件列表</div>
    		<div style="display: flex;" th:if="${enableEdit} == 1">
                <div>
    				<input  class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="drbtn_save" value="导入">
    			</div>
    			<div class="layui-btn layui-btn-normal layui-table-tools" lay-event="addbtn" shiro:hasPermission="business:productbasis:add" style="margin:0 10px;height: 35px;">
    				<p  style="color:white;font-size:14px;"><span class="fa_span">新增明细</span></p>
    			</div>
    			<div>
    				<input  class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="zjbtn_save" value="保存">
    			</div>
    		</div>
    	</div>
    </script>
</div>

<!-- <div>
    <table class="layui-hide" id="jpdhtable" lay-filter="jptable"></table>
    <script type="text/html" id="barDh">
        <a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除</a>
    </script>
    <script type="text/html" id="jptoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">竞品列表</div>
    		<div style="display: flex;" th:if="${enableEdit} == 1">
					<div class="layui-btn layui-btn-normal layui-table-tools" lay-event="addbtn" shiro:hasPermission="business:productbasis:add">
    				<p class="dhicon dh-plus" style="color:white;font-size:14px"><span class="fa_span">新增明细</span></p>
    			</div>
    			<div>
    				<input style="margin-left:10px" class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="btn_save" value="保存">
    			</div>
    		</div>
    	</div>
    </script>
</div> -->
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<!-- <th:block th:include="include :: inlineJS" /> -->

<!-- 明细特殊模板自生成 -->
<div th:each="dfpl:${gridColumnsZJ.dictionaryForPageFieldList}" th:if="${dfpl.fieldFrontType ne 't_text'}" th:remove="tag">
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_decimal' and #strings.containsIgnoreCase(dfpl.fieldFrontTemplet,'p_')}" th:id="'decimal_'+${dfpl.fields}">
        <span>{{d.[[${dfpl.fields}]] + '%'}}</span>
    </script>
    <script type="text/html" th:if="${(dfpl.fieldFrontType eq 't_date' or dfpl.fieldFrontType eq 't_datetime')}" th:id="'date_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'?d.'+${dfpl.fields}+':``}}'" th:fft="${dfpl.fieldFrontType}" class="layui-input layui-table-date" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" autocomplete="off">
        <i class="dhicon dh-calendar icon_date_business" style="z-index:3;font-size:0"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontext'}" th:id="'buttontext_'+${dfpl.fields}">
        <span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontextedit'}" th:id="'buttontextedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" th:onkeyup="inputOnTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_textarea' or (dfpl.fieldFrontType eq 't_textarea' and gridColumnsZJ.readOnly)}" th:id="'textarea_'+${dfpl.fields}">
        <span th:utext="'{{typeof d.'+${dfpl.fields}+' !== \'undefined\' && d.'+${dfpl.fields}+' !== null?d.'+${dfpl.fields}+':\'\'}}'"></span>
        <i class="layui-icon layui-icon-form detail-edit" th:onclick="textareaBox(this,[[${dfpl.fields}]],[[${dfpl.fieldName}]],[[${gridColumnsZJ.readOnly}]])" style="float:right;z-index:999"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdown'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdown_'+${dfpl.fields}">
        <select th:data-field="${dfpl.fields}" th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}" lay-filter="select_table" fft="t_dropdown">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdownedit'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdownedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);height: 30px;margin-top: 1px;margin-left: -7px;" th:onkeyup="inputSearchTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <select th:lay-filter="${dfpl?.fields}+'_select'" autocomplete="off" class="layui-select" lay-search th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_checkbox'}" th:id="'checkbox_'+${dfpl.fields}">
        <div th:utext="'<input type=\'checkbox\' value=\'true\' lay-skin=\'switch\' tName='+${dfpl.fields}+' tIndex=\'{{d.LAY_TABLE_INDEX}}\' lay-filter=\'switchTable\' lay-text=\'是|否\' data-field='+${dfpl.fields}+' {{d.'+${dfpl.fields}+'?\'checked\':\'\'}} '+(${dfpl.fieldFrontEdit or #bools.isTrue(checkProcessTask)}?'':'disabled')+'>'" th:remove="tag"><div>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_file'}" th:id="'file_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" readonly style="border: none;background-color:rgba(0,0,0,0) !important;">
        <i class="layui-icon layui-icon-upload getDetailUpload" tGuid="{{d.guid}}" th:tName="${dfpl.fields}" style="float:right"></i>
    </script>
</div>
<!-- 明细特殊模板自生成 -->
<div th:each="dfpl:${gridColumnsJP.dictionaryForPageFieldList}" th:if="${dfpl.fieldFrontType ne 't_text'}" th:remove="tag">
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_decimal' and #strings.containsIgnoreCase(dfpl.fieldFrontTemplet,'p_')}" th:id="'decimal_'+${dfpl.fields}">
        <span>{{d.[[${dfpl.fields}]] + '%'}}</span>
    </script>
    <script type="text/html" th:if="${(dfpl.fieldFrontType eq 't_date' or dfpl.fieldFrontType eq 't_datetime')}" th:id="'date_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'?d.'+${dfpl.fields}+':``}}'" th:fft="${dfpl.fieldFrontType}" class="layui-input layui-table-date2" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" autocomplete="off">
        <i class="dhicon dh-calendar icon_date_business" style="z-index:3;font-size:0"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontext'}" th:id="'buttontext_'+${dfpl.fields}">
        <span th:text="'{{d.'+${dfpl.fields}+'}}'"></span>
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_buttontextedit'}" th:id="'buttontextedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;left:0;margin:0;height:32px;padding-right:30px" th:onkeyup="inputOnTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <i class="layui-icon layui-icon-more" th:onclick="getMore([[${dfpl.fields}]],{{d.LAY_TABLE_INDEX}},[[${dfpl.fieldName}]],[[${dfpl.fieldSearchType}]])" style="position:absolute;right:8px;z-index:3"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_textarea' or (dfpl.fieldFrontType eq 't_textarea' and gridColumnsJP.readOnly)}" th:id="'textarea_'+${dfpl.fields}">
        <span th:utext="'{{typeof d.'+${dfpl.fields}+' !== \'undefined\' && d.'+${dfpl.fields}+' !== null?d.'+${dfpl.fields}+':\'\'}}'"></span>
        <i class="layui-icon layui-icon-form detail-edit" th:onclick="textareaBox(this,[[${dfpl.fields}]],[[${dfpl.fieldName}]],[[${gridColumnsJP.readOnly}]])" style="float:right;z-index:999"></i>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdown'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdown_'+${dfpl.fields}">
        <select th:data-field="${dfpl.fields}" th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}" lay-filter="select_table" fft="t_dropdown">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_dropdownedit'}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(dfpl.fieldSearchType,'_'),'_')}" th:id="'dropdownedit_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" class="layui-input" style="position:absolute;overflow:hidden;z-index:2;width: calc(100% - 33px);height: 30px;margin-top: 1px;margin-left: -7px;" th:onkeyup="inputSearchTable(this,[[${dfpl.fields}]])" autocomplete="off">
        <select th:lay-filter="${dfpl?.fields}+'_select'" autocomplete="off" class="layui-select" lay-search th:with="map=${@baseinfosimple.getDropdownData(dfpl.fieldSearchType,dfpl.fieldFrontSave,dfpl.fieldFrontShow)}">
            <option></option>
            <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{d.'+${dfpl.fields}+'==\''+${dict.vid}+'\'?\'selected\':\'\'}}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
        </select>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_checkbox'}" th:id="'checkbox_'+${dfpl.fields}">
        <div th:utext="'<input type=\'checkbox\' value=\'true\' lay-skin=\'switch\' tName='+${dfpl.fields}+' tIndex=\'{{d.LAY_TABLE_INDEX}}\' lay-filter=\'switchTable\' lay-text=\'是|否\' data-field='+${dfpl.fields}+' {{d.'+${dfpl.fields}+'?\'checked\':\'\'}} '+(${dfpl.fieldFrontEdit or #bools.isTrue(checkProcessTask)}?'':'disabled')+'>'" th:remove="tag"><div>
    </script>
    <script type="text/html" th:if="${dfpl.fieldFrontType eq 't_file'}" th:id="'file_'+${dfpl.fields}">
        <input type="text" th:value="'{{d.'+${dfpl.fields}+'}}'" readonly style="border: none;background-color:rgba(0,0,0,0) !important;">
        <i class="layui-icon layui-icon-upload getDetailUpload2" tGuid="{{d.guid}}" th:tName="${dfpl.fields}" style="float:right"></i>
    </script>
</div>

<script type="text/template" id="importTpl">
	<form enctype="multipart/form-data" class="mt20 mb10">
		<div class="col-xs-offset-1">
			<input type="file" id="file" name="file"/>
			<div class="mt10 pt5">
				 <a onclick="$.tablelist.importTemplate('/business/productbasis/exporttemplateZJ')" class="btn btn-default btn-xs"><i class="dhicon dh-file-excel-o"></i> 下载模板</a>
			</div>
			<font color="red" class="pull-left mt10">提示：仅允许导入“xls”或“xlsx”格式文件！</font>
		</div>
	</form>
</script>
<!-- 导入明细 -->
<div id="iTable" class="display_no">
	<table class="importTable listext" data-resizable-columns-id="demo-table">
	    <tbody id="itbody"></tbody>
	</table>
</div>

<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "business/productbasis",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var pageType = [[${pageType}]];
	var enableEdit = [[${enableEdit}]];
	var productBasis = [[${productBasis}]];
	var ajaxResult = [[${ajaxResult}]];
	var gridColumnsZJ = [[${gridColumnsZJ}]];
	var gridColumnsJP = [[${gridColumnsJP}]];
	var productInfo = [[${productInfo}]];
    var gridColumns= [[${gridColumns}]];
    var importFields= [[${importFields}]];
	var all_fields= fieldsList;
    console.log(enableEdit,'按钮状态');

    var listData1=[];
    var listData2=[];
    var fieldWidth = {},		//导入列表字段宽度
	filedRequired = {},		//导入列表必填字段
	dateFiled = [],			//导入列表日期字段
	hasNull = false;		//导入数据必填字段有空值
    $.each(gridColumnsZJ.dictionaryForPageFieldList,function(i,v){
    	fieldWidth[v.fields] = v.fieldFrontWidth
    	if(v.fieldFrontRequired)filedRequired[v.fields] = v.fieldName;
    	if(v.fieldFrontType == 't_date')dateFiled.push(v.fields);
    })

	var $,layer,form,table;
    var code=""
    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
		headcom2()
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
            if(is_return) return;
    	   var postStr = [];
		   postStr.push(data.field);
		   $.post("/business/productbasis/editpost",{productBasisItems:JSON.stringify([data.field])},function(res){
				 layer.msg(res.msg);
	       });
           return false;
       });

        var tablestr=''
		$.each(gridColumnsZJ.gridBody,function(i,v){
			if(v.fieldFrontType=="t_decimal"){
				$('#'+v.field+' input').attr('type','number')
			}
		})
        $.each(gridColumnsJP.gridBody,function(i,v){
			if(v.fieldFrontType=="t_datetime"){
                console.log(v.templet)
                if(v.templet){
                    let ids=(v.templet).replace('#','')
                    console.log(ids)
                    tablestr+=``
                }
			}
		})

        
        $.get("/business/productbasis/listzj?pcode="+code,function(res){
                listData1=res.data
	    });
        $.get("/business/productbasis/listjp?pcode="+code,function(res){
                listData2=res.data
	    });

        setTimeout(function(){
            $.tablelist.init({
                elem: '#zjdhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsZJ.totalRow
                , cols: [gridColumnsZJ.gridBody]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '400'
                , done: function (res, curr, count) {
                    listData1 = table.cache.zjdhtable;//每次重载都赋值更新表缓存
                },success:function(a,b,c){
                        console.log(a,b,c)
                }
            });
            $.tablelist.init({
                elem: '#jpdhtable'
                , data: listData2
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsJP.totalRow
                , cols: [gridColumnsJP.gridBody]
                , toolbar: '#jptoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '400'
                , done: function (res, curr, count) {
                    listData2 = table.cache.jpdhtable;//每次重载都赋值更新表缓存
                }
            });
            $('.layui-table-tool-self').hide()
            layuieach()
        },1000)
            
        $.each(gridColumnsZJ.gridNewLine, function (v, k) {//明细新增模板修改默认值
            if (k.substring(0, 1) == '#') gridColumnsZJ.gridNewLine[v] = $(k).val();
        })
        gridColumnsZJ.gridNewLine.deleted = 0;
        //头工具栏事件
        table.on('toolbar(zjtable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
                    console.log(gridColumnsZJ.gridNewLine,999)
                    
                    gridColumnsZJ.gridNewLine.pcode=$('#code').val()
                    var codes=listData1[listData1.length-1]
                    if(codes){
                        var str=codes.code
                        str=str.split("-");
                        str=+str[str.length-1]+1
                        gridColumnsZJ.gridNewLine.code=gridColumnsZJ.gridNewLine.pcode+'-'+(str<10?'0'+str:str)
                    }else{
                        gridColumnsZJ.gridNewLine.code=$('#code').val()+'-01'
                    }
                    console.log(codes,555)
                    // gridColumnsZJ.gridNewLine.code=$('#code').val()
                    listData1.push(gridColumnsZJ.gridNewLine);
				    reloadTable(listData1);
                    form.render();
                    layuieach()
                    break;
                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            };
        });
        //编辑表格监听
        table.on('edit(zjtable)', function (obj) {
            var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
            var oldtext = $(selector).text();// 单元格编辑之前的值
            var editField = obj.field,//编辑单元格fieId
                editRow = obj.data,//编辑单元格行数据
                dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
                isReturn, editValue;
            // if (decimalObj[obj.field] > -1) {//判断是否数值字段
            //     editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
            //     setTableValue('zjdhtable', dataindex, editField, editValue);//通过dom给表格内控件渲染值
            //     listData1[dataindex][editField] = editValue;
            // }
        });
        //监听行事件
        table.on('tool(zjtable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData1 = table.cache.zjdhtable;
                    for (var i = 0; i < listData1.length; i++) if (!listData1[i] || listData1[i].length == 0) listData1.splice(i, 1);//删除一项
				    reloadTable(listData1);
                    break;
            }
        });
        //保存
        form.on('submit(zjbtn_save)', function (data) {
            let cols=gridColumnsZJ.gridBody
            var required=[]
            $.each(cols, function (i, v) {
                var title=v.title
                if(title){
				    if(title.indexOf('<font class="f_red">*</font>') > -1){
                        required.push(v.field)
                    }
                }  
			})
            var isjx=true
            $.each(table.cache.zjdhtable, function (i, v) {
                v.guid=guid
				v.pcode=code
                for(var n=0;n<required.length;n++){
                    var fild=required[n]
                    if(!v[fild]) isjx=false;
                }
			})
            if(!isjx) return layer.msg('请填写必填项');

            $.operate.post(prefix + "/savezjpost", {'pcode':code,'productBasisComponentItems': JSON.stringify(table.cache.zjdhtable),}, function (res) {
                if (res.code == 0){
					layer.msg(res.msg);
				}
            });
        });
        //导入数据
        form.on('submit(drbtn_save)', function (data) {
            if (importFields) {
                thStr = '<tr><th><div style="width:30px;">序号</div></th>';
                $.each(importFields, function (i, val) {
                    fieldWidth[val] = fieldWidth[val] ? fieldWidth[val] : 100;	//默认宽度100px
                    thStr += '<th><div style="width:' + fieldWidth[val] + 'px;">' + i + '</div></th>';
                })
                thStr += '</tr>';
                layer.open({
                    type: 1,
                    area: ['400px', '230px'],
                    fix: false, 
                    offset: '10%',
                    maxmin: true,
                    shade: 0.3,
                    title: '导入',
                    content: $('#importTpl').html(),
                    btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
                    shadeClose: true,
                    zIndex: 1000,
                    btn1: function (index, layero) {
                        var file = layero.find('#file');
                        if (!file[0]['value']) {
                            layer.msg("请选择文件！");
                            return false;
                        }
                        var imRes = importListExcel(file[0], importFields, 'amazonanalysis');
                    }
                });
            } else {
                $.modal.alertWarning("后台未返回导入模板对象！");
            }
        })
    
		
        $.each(gridColumnsJP.gridNewLine, function (v, k) {//明细新增模板修改默认值
            if (k.substring(0, 1) == '#') gridColumnsJP.gridNewLine[v] = $(k).val();
        })
        gridColumnsJP.gridNewLine.deleted = 0;
        //头工具栏事件
        table.on('toolbar(jptable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
                    listData2.push(gridColumnsJP.gridNewLine);
				    jpreloadTable(listData2);
                    form.render();
                    layuieach()
                    break;
                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            };
        });
        //编辑表格监听
        table.on('edit(jptable)', function (obj) {
            var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
            var oldtext = $(selector).text();// 单元格编辑之前的值
            var editField = obj.field,//编辑单元格fieId
                editRow = obj.data,//编辑单元格行数据
                dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
                isReturn, editValue;
        });
        //监听行事件
        table.on('tool(jptable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData2 = table.cache.jpdhtable;
                    for (var i = 0; i < listData2.length; i++) if (!listData2[i] || listData2[i].length == 0) listData2.splice(i, 1);//删除一项
				    jpreloadTable(listData2);
                    break;
            }
        });

        form.on('submit(btn_save)', function (data) {
            let cols=gridColumnsJP.gridBody
            var required=[]
            $.each(cols, function (i, v) {
                var title=v.title
                if(title){
				    if(title.indexOf('<font class="f_red">*</font>') > -1){
                        required.push(v.field)
                    }
                }  
			})
            var isjx=true
            $.each(table.cache.jpdhtable, function (i, v) {
                v.guid=guid
				v.pcode=code
                for(var n=0;n<required.length;n++){
                    var fild=required[n]
                    if(!v[fild]){
                        isjx=false
                    } 
                }
			})
            if(!isjx) return layer.msg('请填写必填项');
            $.operate.post(prefix + "/savejppost", {'pcode':code,'productBasisCompeteItems': JSON.stringify(table.cache.jpdhtable),}, function (res) {
                if (res.code == 0){
					layer.msg(res.msg);
				}
            });
        });

        assemblyhead()

        function layuieach(){
            $(".layui-table-date").each(function (i) {
	        	laydate.render({
	        		elem: this,
                    type: 'date',
            		trigger: 'click',
                    btns:['clear', 'now'],
            		done: function (value, date) {
            			var elemtr=$(this.elem).parents('tr').index();
            			var elem=$(this.elem).parents('td');
            			var datafield = elem.attr("data-field");
            			if (listData1[elemtr]) {
            				listData1[elemtr][datafield] = value;
            			}
            		}
	        	});
	        });
            $(".layui-table-date2").each(function (i) {
	        	laydate.render({
	        		elem: this,
                    type: 'date',
            		trigger: 'click',
                    btns:['clear', 'now'],
            		done: function (value, date) {
            			var elemtr = $(this.elem).parents('tr').index();
            			var elem = $(this.elem).parents('td');
            			var datafield = elem.attr("data-field");
            			if (listData2[elemtr]) {
            				listData2[elemtr][datafield] = value;
            			}
            		}
	        	});
	        });
            $(".getDetailUpload").each(function(){
                var that=this
                upload.render({
                    elem: that,
	                url: '/system/fileinfo/uploadmailimg',
	                accept: 'images',
	            	before: function(obj){
                        //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                          console.log(index, file, result)
                        });
                    },
	                done: function (res) {
                        //如果上传失败
                        if (res.errno > 0) {
                            return layer.msg('上传失败');
                        }else{
	            			layer.msg('上传成功');
                            layui.$(that).prevAll('input').value(res.data[0])
                            var elemtr = $(this.elem).parents('tr').index();
            			    var elem = $(this.elem).parents('td');
            			    var datafield = elem.attr("data-field");
                            if (res && listData1[elemtr]) {
            			    	listData1[elemtr][datafield] = res.data[0];
            			    }
	            		}
                    },error: function (err) {
                        //演示失败状态，并实现重传
	                	console.log(err)
                    }
                });
            })

            $(".getDetailUpload2").each(function(){
                var that=this
                upload.render({
                    elem: that,
	                url: '/system/fileinfo/uploadmailimg',
	                accept: 'images',
	            	before: function(obj){
                        //预读本地文件示例，不支持ie8
                        obj.preview(function(index, file, result){
                          console.log(index, file, result)
                        });
                    },
	                done: function (res) {
                        //如果上传失败
                        if (res.errno > 0) {
                            return layer.msg('上传失败');
                        }else{
	            			layer.msg('上传成功');
                            layui.$(that).prevAll('input').val(res.data[0])
                            var elemtr = $(this.elem).parents('tr').index();
            			    var elem = $(this.elem).parents('td');
            			    var datafield = elem.attr("data-field");
                            if (res && listData2[elemtr]) {
            			    	listData2[elemtr][datafield] = res.data[0];
            			    }
	            		}
                    },error: function (err) {
                        //演示失败状态，并实现重传
	                	console.log(err)
                    }
                });
            })
        }

		// beforeInit();//表单初始化之前的动作集合
		// layui.element.render();

    });
    

	function reloadTable(data){
        table.reload('zjdhtable', {data : data});
    }

	function jpreloadTable(data){
        table.reload('jpdhtable', {data : data});
    }
    
    /*批量请求导入数据
     *tobj：导入数据对象
     *startNum：从第几条开始导入
     *oneImportNum：每次导入条数
     *allImportNum：总数据量
     *times：导入次数
     */
     function eachImport(tobj,startNum, oneImportNum, allImportNum, times, timeNum){
    	var importObj = [], inum = startNum, importBl='0%';
    	for(var i = startNum; i < allImportNum; i++){
    		if(i >= allImportNum)break;
    		inum = i + 1 ;
    		importObj.push(tobj[i]);
    	}
        listData1=listData1.concat(importObj);
    	$.ajaxSettings.async = false;
        showloadings(false);
        layer.closeAll();
        table.reload('zjdhtable', {data : listData1});
    	// $.post("/hr/amazonanalysis/importdatapost", {'infoItems':JSON.stringify(importObj, null, 2)}, function(result) {
    	// 	importBl = (inum/allImportNum)*100;
    	// 	importObj = [];
    	// 	timeNum += 1;
    		
    	// 	layer.msg(result.msg)
    	// 	if(result.code==0){
    	// 		location.reload();
    	// 	}
        // },"json");
    }

	function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');            
        var r = window.location.search.substr(1).match(reg);            
        if (r != null) {            
         return unescape(r[2]);            
        }            
        return null;
    }
	var guid=getQueryString("guid");

	/*]]>*/
</script>

</body>
</html>